package com.learn.core.controller.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.learn.common.annotation.Log;
import com.learn.common.annotation.UserLoginToken;
import com.learn.common.enums.BusinessType;
import com.learn.common.enums.OperatorType;
import com.learn.common.enums.ResultEnum;
import com.learn.common.utils.*;
import com.learn.common.utils.poi.ExcelUtils;
import com.learn.common.utils.result.CommonResult;
import com.learn.core.domain.*;
import com.learn.core.domain.view.UserDetailsGather;
import com.learn.core.dto.LQuestionsDTO;
import com.learn.core.dto.QuestionsOptionDTO;
import com.learn.core.service.*;
import com.learn.framework.web.controller.WebController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Description
 *
 * @author zhaohongyu
 * @ClassName LQuestionsCountroller
 * @date 2021.03.22 10:03
 * @describe 试题
 */
@Api("试题")
@RestController
@RequestMapping("/manager/questions")
@CrossOrigin
public class LQuestionsController extends WebController<LQuestions> {

    @Autowired
    private ILQuestionsService ilQuestionsService;
    @Autowired
    private ILOptionService ilOptionService;
    @Autowired
    private ILQuestionsTypeService ilQuestionsTypeService;
    @Autowired
    private ILQuestionsSortService ilQuestionsSortService;

    //列表
    @ApiOperation(value = "获取列表")
    @UserLoginToken()
    @PostMapping("/list")
    public PageResult<LQuestions> list(@RequestBody LQuestionsDTO lQuestionsDTO){
        try {
            if (lQuestionsDTO==null||lQuestionsDTO.getPage()==null||lQuestionsDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lQuestionsDTO.getPage(),lQuestionsDTO.getRows());
            QueryWrapper<LQuestions> queryWrapper = new QueryWrapper<>();
            if(StringUtils.isNotEmpty(lQuestionsDTO.getQuestionsSortId()))
                queryWrapper.eq("questions_sort_id",lQuestionsDTO.getQuestionsSortId());
            if(StringUtils.isNotEmpty(lQuestionsDTO.getQuestionsDifficulty()))
                queryWrapper.eq("questions_difficulty",lQuestionsDTO.getQuestionsDifficulty());
            if(StringUtils.isNotEmpty(lQuestionsDTO.getQuestionsType()))
                queryWrapper.eq("questions_type",lQuestionsDTO.getQuestionsType());
            if(StringUtils.isNotEmpty(lQuestionsDTO.getKnowledge()))
                queryWrapper.eq("knowledge",lQuestionsDTO.getKnowledge());
            queryWrapper.orderByAsc("questions_seq");
            Page<LQuestions> lQuestions = (Page<LQuestions>)ilQuestionsService.list(queryWrapper);
            if (CollectionUtils.isEmpty(lQuestions)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            // 查询选项
            for (LQuestions lQuestion: lQuestions) {
                QueryWrapper<LOption> queryLOption = new QueryWrapper<LOption>();
                queryLOption.eq("questions_id",lQuestion.getQuestionsId());
                List<LOption> lOptionList = ilOptionService.list(queryLOption);
                lQuestion.setlOptionList(lOptionList);
                LQuestionsType lQuestionsType = ilQuestionsTypeService.getById(lQuestion.getQuestionsType());
                if(null != lQuestionsType)
                    lQuestion.setQuestionsTypeName(lQuestionsType.getQuestionsTypeName());
                LQuestionsSort lQuestionsSort = ilQuestionsSortService.getById(lQuestion.getQuestionsSortId());
                if(null != lQuestionsSort)
                    lQuestion.setQuestionsSortName(lQuestionsSort.getQuestionsSortName());
            }
            // 返回
            return new PageResult(lQuestions.getTotal(), lQuestions, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }

    //更新
    @ApiOperation(value = "更新")
    @PostMapping("/edit")
    @UserLoginToken
    @Log(title = "更新试题", businessType = BusinessType.UPDATE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> edit(@RequestBody LQuestions lQuestions, HttpServletRequest request) {
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        if(lQuestions!=null){
            lQuestions.setUpdateTime(new Date());
            lQuestions.setUpdateUser(userId);
            if(ilQuestionsService.updateById(lQuestions)){
                // 修改选项
                List<LOption> lOptionList = lQuestions.getlOptionList();
                ilOptionService.updateBatchById(lOptionList);
                return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
            }
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    //新增
    @ApiOperation(value = "添加")
    @PostMapping("/add")
    @UserLoginToken
    @Log(title = "添加试题", businessType = BusinessType.INSERT, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> add(@RequestBody LQuestions lQuestions, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if(lQuestions!=null) {
                if (StringUtils.isEmpty(lQuestions.getKnowledge())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_QUESTIONS_KNOWLEDGE);
                }
                if (StringUtils.isEmpty(lQuestions.getQuestionsType())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_QUESTIONS_TYPE);
                }
                if (StringUtils.isEmpty(lQuestions.getQuestionsFraction())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_QUESTIONS_FRACTION);
                }
                if (StringUtils.isEmpty(lQuestions.getQuestionsDifficulty())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_QUESTIONS_DIFFICULTY);
                }
                if (StringUtils.isEmpty(lQuestions.getQuestionsSortId())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_QUESTIONS_SORT);
                }
                if (StringUtils.isEmpty(lQuestions.getQuestionsContent())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_QUESTIONS_CONTENT);
                }
                if (StringUtils.isEmpty(lQuestions.getQuestionsAnswer())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_QUESTIONS_ANSWER);
                }
                lQuestions.setCreateUser(userId);
                lQuestions.setCreateTime(new Date());
                if (ilQuestionsService.save(lQuestions)) {
                    // 新增选项
                    List<LOption> lOptionList = lQuestions.getlOptionList();
                    for(LOption lOption:lOptionList){
                        lOption.setQuestionsId(lQuestions.getQuestionsId());
                    }
                    ilOptionService.saveBatch(lOptionList);
                    return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
                }
            }
        }catch (Exception e){
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return  (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }


    //删除
    @ApiOperation(value = "删除")
    @PostMapping("/del")
    @UserLoginToken
    @Log(title = "删除试题", businessType = BusinessType.DELETE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> del(@RequestBody LQuestions lQuestions){
        try {
            if(lQuestions!=null){
                if(lQuestions.getQuestionsId()!=null){
                    QueryWrapper<LQuestions> queryWrapper = new QueryWrapper<LQuestions>();
                    queryWrapper.in(true, "questions_id", lQuestions.getQuestionsId());
                    if(ilQuestionsService.remove(queryWrapper)){
                        // 删除选项
                        QueryWrapper<LOption> querylOption = new QueryWrapper<LOption>();
                        querylOption.eq("questions_id",lQuestions.getQuestionsId());
                        ilOptionService.remove(querylOption);
                        return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
                    }
                }
            }
        }catch (Exception e)
        {
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    //TODO 导入试题
    @ApiOperation(value = "导入试题")
    @PostMapping("/uploadQuestionExcel")
    @UserLoginToken
    @Log(title = "导入试题", businessType = BusinessType.IMPORT, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> uploadQuestionExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);

        String fileName = file.getOriginalFilename();
        int one = fileName.lastIndexOf(".");
        String Suffix = fileName.substring((one+1),fileName.length());
        if (!"xls".equals(Suffix) && !"xlsx".equals(Suffix)) {
            return (CommonResult)ResultUtil.error(ResultEnum.FILE_FORMAT_ERROR);
        }
        ExcelUtils excelUtils = new ExcelUtils(QuestionsOptionDTO.class);
        try {
            List<QuestionsOptionDTO> list = excelUtils.importExcel(file.getInputStream());
            for (QuestionsOptionDTO dto : list) {
                LQuestions lQuestions = new LQuestions();
                lQuestions.setQuestionsContent(dto.getQuestionsContent());
                lQuestions.setQuestionsAnswer(dto.getQuestionsAnswer());
                lQuestions.setQuestionsExplain(dto.getQuestionsExplain());
                if(null != dto.getQuestionsFraction()){
                    lQuestions.setQuestionsFraction(Integer.parseInt(dto.getQuestionsFraction()));
                }
                if(StringUtils.isNotEmpty(dto.getQuestionsDifficulty())){
                    if("容易".equals(dto.getQuestionsDifficulty())){
                        lQuestions.setQuestionsDifficulty(1);
                    }else if("较易".equals(dto.getQuestionsDifficulty())){
                        lQuestions.setQuestionsDifficulty(2);
                    }else if("一般".equals(dto.getQuestionsDifficulty())){
                        lQuestions.setQuestionsDifficulty(3);
                    }else if("较难".equals(dto.getQuestionsDifficulty())){
                        lQuestions.setQuestionsDifficulty(4);
                    }else if("非常难".equals(dto.getQuestionsDifficulty())){
                        lQuestions.setQuestionsDifficulty(5);
                    }
                }
                if(StringUtils.isNotEmpty(dto.getQuestionsType())){
                    QueryWrapper<LQuestionsType> typeQueryWrapper = new QueryWrapper<>();
                    typeQueryWrapper.eq("questions_type_name",dto.getQuestionsType());
                    LQuestionsType lQuestionsType = ilQuestionsTypeService.getOne(typeQueryWrapper);
                    if(null != lQuestionsType)
                    lQuestions.setQuestionsType(lQuestionsType.getQuestionsTypeId());
                }
                if(StringUtils.isNotEmpty(dto.getQuerstionsSort())){
                    QueryWrapper<LQuestionsSort> sortQueryWrapper = new QueryWrapper<>();
                    sortQueryWrapper.eq("questions_sort_name",dto.getQuestionsType());
                    LQuestionsSort lQuestionsSort = ilQuestionsSortService.getOne(sortQueryWrapper);
                    if(null != lQuestionsSort)
                        lQuestions.setQuestionsType(lQuestionsSort.getQuestionsSortId());
                }
                lQuestions.setKnowledge(dto.getKnowledge());
                lQuestions.setCreateUser(userId);
                lQuestions.setCreateTime(new Date());
                if (ilQuestionsService.save(lQuestions)) {
                    // 新增选项
                    String option = dto.getOption();
                    if(StringUtils.isNotEmpty(option)){
                        List<LOption> lOptionList = new ArrayList<>();
                        String [] op = option.split(",");
                        char c = 'A';
                        for(String str : op){
                            LOption lOption = new LOption();
                            lOption.setQuestionsId(lQuestions.getQuestionsId());
                            lOption.setOptionNum(String.valueOf(c));
                            lOption.setOptionContent(str);
                            c++;
                            lOptionList.add(lOption);
                        }
                        ilOptionService.saveBatch(lOptionList);
                    }
                    return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
                }
            }
            return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
    }
}
